package cn.aiseminar.aisinterphone;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class PhoneMessageAdapter extends BaseAdapter {
	private static LayoutInflater mInflater = null;
	private ArrayList<PhoneMessage> mMessageList = null;
	
	public static final int SENDER_TYPE_THIS = 0;
	public static final int SENDER_TYPE_THAT = 1;
		
	public PhoneMessageAdapter(Context context, ArrayList<PhoneMessage> messageList)
	{
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mMessageList = messageList;
		if (null == mMessageList)
		{
			mMessageList = new ArrayList<PhoneMessage>();
		}
	}
	
	public void add(String message, int senderType)
	{
		PhoneMessage pm = new PhoneMessage();
		pm.setSenderType(senderType);
		pm.setSendTime(Calendar.getInstance().getTime());
		pm.setContent(message);
		
		mMessageList.add(pm);
		this.notifyDataSetChanged();
	}
	
	@Override
	public int getCount() 
	{
		if (null == mMessageList)
		{
			return 0;
		}
		
		return mMessageList.size();
	}

	@Override
	public Object getItem(int position) 
	{
		if (null == mMessageList)
		{
			return null;
		}
		
		return mMessageList.get(position);
	}

	@Override
	public long getItemId(int position) 
	{
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) 
	{
		if (null == convertView)
		{
			convertView = mInflater.inflate(R.layout.message_item, null);
		}
		TextView tvSendDate = (TextView) convertView.findViewById(R.id.tvSendTime);
		ImageView imageThatHeader = (ImageView) convertView.findViewById(R.id.imageThatHeader);
		ImageView imageThisHeader = (ImageView) convertView.findViewById(R.id.imageThisHeader);
		TextView tvContent = (TextView) convertView.findViewById(R.id.tvMessageContent);
		
		PhoneMessage mess = mMessageList.get(position);
		tvSendDate.setText(DateFormat.getDateTimeInstance().format(mess.getSendTime()));
		if (SENDER_TYPE_THIS == mess.getSenderType())
		{
			imageThatHeader.setVisibility(View.INVISIBLE);
			imageThisHeader.setVisibility(View.VISIBLE);
			tvContent.setBackgroundResource(R.drawable.chatto_bg_voice_playing);
		}
		else
		{
			imageThatHeader.setVisibility(View.VISIBLE);
			imageThisHeader.setVisibility(View.INVISIBLE);
			tvContent.setBackgroundResource(R.drawable.chatfrom_bg_voice_playing);
		}
		tvContent.setText(mess.getContent());
		
		return convertView;
	}

}
